<?php

namespace app\command;

use app\model\AdminAgent;
use app\model\AgentDistribution;
use app\model\DistributionSetting;
use app\model\User;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use util\Logger;

class AgentUserUpgradeCommand extends Command
{
	protected function configure()
	{
		$this->setName('agent-user-upgrade')
			->setDescription('检查合作商用户升级');
	}

	protected function execute(Input $input, Output $output)
	{
		try {
			$sys_setting = DistributionSetting::field('invite, income, task_condition')->where('uuid', 'setting')->find();
			$setting     = [];
			User::field('id, total, invite_count, agent_id')
				->where('status', User::STATUS_YES)
				->where('agent_id', 'gt', 0)
				->where('level', 'neq', 2)->chunk(100, (function ($users) use (&$setting, $sys_setting) {
					foreach ($users as $user) {
						if (!isset($setting[$user['agent_id']])) {
							$agent_setting = AgentDistribution::field('ad.id, ad.agent_id, ad.invite, ad.income, ad.task_condition, a.level_count')
								->alias('ad')
								->leftJoin('admin_agent a', 'a.id = ad.agent_id')
								->where('agent_id', $user['agent_id'])
								->find();
							if ($agent_setting) {
								$setting[$user['agent_id']] = $agent_setting->toArray();
							} else {
								$setting[$user['agent_id']] = $sys_setting->toArray();
							}
						}
						//合作商没有升级次数
						if (empty($setting[$user['agent_id']]['level_count'])) {
							continue;
						}
						$task_condition = $setting[$user['agent_id']]['task_condition'];
						if ($task_condition == 0) {
							continue;
						}
						$setting['level'] = json_decode($setting['level'], true);

						$invite    = $setting[$user['agent_id']]['level']['invite'];
						$income    = $setting[$user['agent_id']]['income'];
						$has_level = false;
						//完成任意一个任务升级
						if ($task_condition == 1) {
							if ($user['total'] >= $income || $user['invite_count'] >= $invite) {
								$user->level = 2;
								$user->save();
								$has_level = true;
							}
						} else {
							//需要完成两个任务升级
							if ($user['total'] >= $income && $user['invite_count'] >= $invite) {
								$user->level = 2;
								$user->save();
								$has_level = true;
							}
						}
						//如果有升级扣减合作商次数
						if ($has_level) {
							AdminAgent::where('id', $user['agent_id'])->setDec('level_count');
						}
					}
				}));
		} catch (\Exception $e) {
			Logger::error($e->getMessage());
			exit;
		}

	}
}
